package com.loren.demo03.tcp3.codec;

import com.loren.demo03.tcp0.CustomProtocol;
import com.loren.demo03.tcp0.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

public class CustomMessageCodec extends MessageToMessageCodec<ByteBuf, CustomProtocol> {

    @Override
    protected void encode(ChannelHandlerContext ctx, CustomProtocol msg, List<Object> out) {
        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeByte(CustomProtocol.DATA_HEAD);
        byteBuf.writeInt(msg.getLength());
        byteBuf.writeBytes(msg.getContent());
        byteBuf.writeByte(CustomProtocol.DATA_TAIL);
        out.add(byteBuf);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        new MessageCodec().decode(in, out);
    }
}
